package com.estar.assistsurvy.service;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.os.Environment;

import com.estar.app.appsrvycabx.domain.DataVO;
import com.estar.app.appsrvyspds.domain.ReturnSubVideoSrvyVO;
import com.estar.app.appsrvyspds.domain.UploadPicVO;
import com.estar.assistsurvey.entity.ImageVO;
import com.estar.assistsurvy.constant.Constants;
import com.estar.assistsurvy.encode.Base64;
import com.estar.assistsurvy.entity.VOBase;
import com.estar.assistsurvy.utils.LogUtil;
import com.estar.assistsurvy.utils.NetWorkUtil;
import com.estarimage.EstarImage;
import com.socks.okhttp.plus.OkHttpProxy;
import com.socks.okhttp.plus.callback.OkCallback;
import com.socks.okhttp.plus.parser.OkTextParser;
import com.thoughtworks.xstream.XStream;

import org.litepal.crud.DataSupport;

import okhttp3.Response;


public class ImageService extends IntentService {
    AlarmManager am = null; // 提醒管理类
    private int pertime = 60; // 定位间隔 单位：秒
    PendingIntent pendingIntent;

    private boolean isUpload = false;//判断当前是否有图片正在上传

    public ImageService() {
        super("ImageService");
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);


    }


    @Override
    protected void onHandleIntent(Intent intent) {
        notifyService();

        if (!NetWorkUtil.isNetworkAvailable(this)) {
            LogUtil.f("image", "设备无网络。图片不上传");
            return;
        }
        if (isUpload) {
            LogUtil.f("image", "有图片正在上传");
            return;
        }
        List<ImageVO> imageVOs = DataSupport.where("uploadState <> '1' and currentUploadCount < 5").order("createTm desc").find(ImageVO.class);
        if (imageVOs != null && imageVOs.size() > 0) {
            for (ImageVO imageVO : imageVOs) {
                upload(imageVO);
            }

        } else {
            LogUtil.i("image", "当前没有查到待上传的图片");
        }

    }

    public void upload(ImageVO imageVO) {

        DataVO dataVO = new DataVO();
        dataVO.setMethod("uploadImg");
        dataVO.setAction("UploadImge");
        List<VOBase> list = new ArrayList<>();
        dataVO.setList(list);
        UploadPicVO uploadPicVO = new UploadPicVO();
        uploadPicVO.setCarNo(imageVO.getCarNo());
        uploadPicVO.setRptNo(imageVO.getRptNo());
        uploadPicVO.setCompCde(imageVO.getCompCde());
        uploadPicVO.setDptCde(imageVO.getDptCde());
        uploadPicVO.setPicName(imageVO.getPicName());
        uploadPicVO.setPicPath(imageVO.getPicPath());
        uploadPicVO.setPicDescription(imageVO.getPicDescription());
        uploadPicVO.setLatitude(imageVO.getLatitude());
        uploadPicVO.setLongitude(imageVO.getLongitude());
        uploadPicVO.setCreateTm(imageVO.getCreateTm());
        try {
            uploadPicVO.setPicData(convertBase64(imageVO.getPicPath()));
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.i("image", "转base64失败");
            return;
        }
        uploadPicVO.setClaimTaskId(imageVO.getClaimTaskId());
        uploadPicVO.setClaimTaskType(imageVO.getClaimTaskType());
        uploadPicVO.setLossEmpCde(imageVO.getLossEmpCde());
        uploadPicVO.setLossEmpNme(imageVO.getLossEmpNme());
        list.add(uploadPicVO);
        try {
           Response response =  OkHttpProxy.postData().url(Constants.VIDEO_SERVICE).setDataXml(dataVO).execute();
            if(response.isSuccessful()){
                InputStream is = response.body().byteStream();
                InputStreamReader isr = new InputStreamReader(is, "GB2312");
                char[] bt = new char[1024];
                String countTaskStr = "";
                int len;
                while ((len = isr.read(bt)) != -1) {
                    countTaskStr += new String(bt, 0, len);
                }
                isr.close();
                is.close();

                // String countTaskStr = arg0.body().string();
                XStream xStream = new XStream();
                xStream.alias(DataVO.class.getName(), DataVO.class);
//                LogUtil.i("111","图片上传返回："+countTaskStr);
            }
        } catch (IOException e) {
            e.printStackTrace();
            LogUtil.i("111", e.getMessage());
        }
//        (new OkCallback<String>(new OkTextParser() {
//        }) {
//
//            @Override
//            public void onSuccess(int code, String string) {
//                LogUtil.i("111","图片上传返回："+string);
//            }
//
//            @Override
//            public void onFailure(Throwable e) {
//                LogUtil.i("111", e.getMessage());
//            }
//        });

    }

    /**
     * 图片转换为base64编码
     *
     * @param filePath
     * @return
     * @throws IOException
     */
    public String convertBase64(String filePath) throws IOException {

        InputStream fis = null;
        // 上传前做图片损坏验证,如果图片损坏就用特定图片替代上传
        EstarImage estar = new EstarImage();
        if (estar.CheckJPegFile(filePath) == false) {
            fis = this.getResources().getAssets().open("error_upload.jpg");
        } else {
            fis = new FileInputStream(filePath);
        }

        byte[] buffer = new byte[fis.available()];
        fis.read(buffer);
        fis.close();
        String text = Base64.encodeBase64String(buffer);
        System.gc();
        return text;
    }

    /**
     * 通过闹铃服务来设定定位间隔
     */
    private synchronized void notifyService() {
        Calendar calendar = Calendar.getInstance(); // 赋值
        calendar.setTimeInMillis(System.currentTimeMillis()); // 设置系统时间

        Intent intent = new Intent(this, ImageService.class);
        intent.putExtra("pending", "pending");
        pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        if (am != null) // 提醒服务类不为空，先取消
        {
            am.cancel(pendingIntent);
        }
        am = (AlarmManager) getSystemService(ALARM_SERVICE);
        // 设置闹钟
        am.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis() + (pertime * 1000),
                pendingIntent);
    }
}
